package com.ruoyi.framework.security.jsonlogin;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 默认的表单登录用户实现
 *
 * @author xueyu
 */
@Slf4j
@Service(value = "loginUserDetailServiceImpl")
public class LoginUserDetailServiceImpl implements UserDetailsService {

    private final ISysUserService iSysUserService;

    private final SysPermissionService sysPermissionService;

    @Autowired
    public LoginUserDetailServiceImpl(ISysUserService iSysUserService, SysPermissionService sysPermissionService) {
        this.iSysUserService = iSysUserService;
        this.sysPermissionService = sysPermissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = iSysUserService.selectUserByUserName(username);
        if (Objects.isNull(user)) {
            log.error("没有根据用户名:{}找到相关的用户信息!", username);
            return null;
        }
        if (user.getDelFlag().equals(UserStatus.DELETED.getCode())) {
            log.error("用户:{}已经被删除!", user);
            return null;
        }
        return createLoginUser(user);
    }

    private UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, sysPermissionService.getMenuPermission(user));
    }
}
